#coding:utf8
'''
Created on 2016年6月12日

@author: zhangjinrui
'''

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import AxesGrid
import matplotlib.animation as animation
from matplotlib.widgets import Button
from DataReader import DataReader
import threading
import time

path = '../../data'
padl = 0.05
padr = 0.05
padb = 0.2
padt = 0.1
pad_each = 0.005
height = 0.8

class presentInfo:
    
    def __init__(self, f):
        
        self.figure = f
        self.data_reader = DataReader(path)
        self.host_grid = {}
        self.hosts = self.data_reader.get_hostnames()
        self.init_grids()
    
    def init_grids(self):
        self.host_count = self.data_reader.get_host_count()
        self.width = ((1 - padl - padr) - (pad_each * (self.host_count - 1))) / self.host_count
        self.height = height
        for i in range(self.host_count):
            #设计布局
            self.host_grid[self.hosts[i]] = self.add_one_host(i)
            #初始化图标状态
            self.init_one_host_axes(self.hosts[i])
            
    
    def add_one_host(self,pos):
        height = (1 - padt - padb) / 4
        
        rect = padl + pos * (self.width + pad_each), padb + 3 * height, self.width, height 
        ax1 = self.figure.add_axes(rect)
        self.fade_xlabel(ax1)
        
        rect = padl + pos * (self.width + pad_each), padb + 2 * height, self.width, height 
        ax2 = self.figure.add_axes(rect)
        self.fade_xlabel(ax2)
        
        rect = padl + pos * (self.width + pad_each), padb + 1 * height, self.width, height 
        ax3 = self.figure.add_axes(rect)
        self.fade_xlabel(ax3)
        
        rect = padl + pos * (self.width + pad_each), padb + 0 * height, self.width, height 
        ax4 = self.figure.add_axes(rect)
        
        if pos != 0 :
            self.fade_ylabel(ax1)
            self.fade_ylabel(ax2)
            self.fade_ylabel(ax3)
            self.fade_ylabel(ax4)
        
        return list([ax1,ax2,ax3,ax4])
    
    def fade_xlabel(self,ax):
        ax.set_xticklabels(range(10), visible = False)
    
    def fade_ylabel(self,ax):
        ax.set_yticklabels(range(10), visible = False)
    
    def add_one_grid(self,pos):
        rect = padl + pos * (self.width + pad_each) , padb, self.width, self.height
        print rect
        grid = AxesGrid(self.figure, rect,  
#         grid = AxesGrid(self.figure, 100 + self.host_count*10 + pos + 1,  
                        nrows_ncols=(4, 1),
                        axes_pad=0.0,
                        share_all=False,
#                         add_all = True
#                         label_mode="L",
#                         cbar_location="top",
#                         cbar_mode="single",
                        )
        return grid
    
    #为了animate..
    def get_data(self):
        while True:
            yield self.data_reader.get_one_set_data()
    
    def update_data(self):
        data = self.data_reader.get_one_set_data()
        for i in range(len(self.hosts)):
            self.set_data_to_one_host(i, self.hosts[i], data[self.hosts[i]])
        self.figure.canvas.draw()
#         self.set_data_to_one_host(0, self.hosts[0], data[self.hosts[0]])
        
    
    def init_one_host_axes(self, name):
        tx = [0,1,2,3,4,5,6,7,8,9]
        ty = [0,0,0,0,0,0,0,0,0,0]
        
        cpu_axes = self.host_grid[name][0]
        memory_axes = self.host_grid[name][1]
        disk_axes = self.host_grid[name][2]
        net_axes = self.host_grid[name][3]
        
        cpu_axes.plot(tx,ty)
        cpu_axes.set_ylim(0,100)
        cpu_axes.set_xlim(0,10)
        
        
        memory_axes.plot(tx,ty)
        memory_axes.set_ylim(0,100)
        memory_axes.set_xlim(0,10)
        
        
        disk_axes.plot(tx,ty)
        disk_axes.plot(tx,ty)
        disk_axes.set_ylim(0,10)
        disk_axes.set_xlim(0,10)
        
        net_axes.plot(tx,ty)
        net_axes.plot(tx,ty)
        net_axes.set_ylim(0,10)
        net_axes.set_xlim(0,10)
        net_axes.set_xticks(range(10))
        
    def but_on_click(self, event):
        print 'click me'

def but_on_click(event):
    ani_update_data(f, host_grid, hosts, data_reader)

def ani_update_data(figure, host_grid, hosts, data_reader):
    print time.time()
    data = data_reader.get_one_set_data()
    for i in range(len(hosts)):
        set_data_to_one_host(figure, host_grid, i, hosts[i], data[hosts[i]])
    f.canvas.draw()

def timer_update():
    ani_update_data(f, host_grid, hosts, data_reader)

def data_gen():
    while True:
        yield data_reader.get_one_set_data()

def ani_update(data):
    for i in range(len(hosts)):
        set_data_to_one_host(f, host_grid, i, hosts[i], data[hosts[i]])

def set_data_to_one_host(figure,host_grid, pos, name, dat):
        cpu_axes = host_grid[name][0]
        memory_axes = host_grid[name][1]
        disk_axes = host_grid[name][2]
        net_axes = host_grid[name][3]
        
        #更新CPU的值
        line, = cpu_axes.get_lines()
        y = list(line.get_ydata())
        y.append(dat['cpu_all_percent'])
        if len(y) > 10:
            del y[0]
        x = range(len(y))
        line.set_data(x , y)
        
        #更新内存的值
        line, = memory_axes.get_lines()
        y = list(line.get_ydata())
        y.append(dat['memory_percent'])
        if len(y) > 10:
            del y[0]
        x = range(len(y))
        line.set_data(x, y)
        
        #更新磁盘的值
        lines = disk_axes.get_lines()
        #先更新读入速度
        y = list(lines[0].get_ydata())
        y.append(dat['disk_read_speed'])
        if len(y) > 10:
            del y[0]
        x = range(len(y))
        lines[0].set_data(x , y)
        #更新写入速度
        y = list(lines[1].get_ydata())
        y.append(dat['disk_write_speed'])
        if len(y) > 10:
            del y[0]
        x = range(len(y))
        lines[1].set_data(x , y)
        maxv = np.max(y)
        if maxv > 100:
            maxv += 10
        else:
            maxv = 100
        disk_axes.set_ylim(0,maxv)
        disk_axes.set_yticks((0,maxv / 2,maxv))
        
        #更新网络的值
        lines = net_axes.get_lines()
        #更新发送速度
        y = list(lines[0].get_ydata())
        y.append(dat['net_send_speed'])
        if len(y) > 10:
            del y[0]
        x = range(len(y))
        lines[0].set_data(x , y)
        #更新接受速度
        y = list(lines[1].get_ydata())
        y.append(dat['net_rec_speed'])
        if len(y) > 10:
            del y[0]
        x = range(len(y))
        lines[1].set_data(x , y)
        maxv = np.max(y)
        if maxv > 10:
            maxv += 10
        else:
            maxv = 10
        net_axes.set_ylim(0,maxv)
        net_axes.set_yticks((0,maxv / 2,maxv))

host_grid = None
data_reader = None
hosts = None

f = plt.figure(1, figsize=(20,10))
p = presentInfo(f)

host_grid = p.host_grid
data_reader = p.data_reader
hosts = p.hosts


axnext = plt.axes([0.45,0.1,0.05,0.05])
but = Button(axnext, 'Next')

ani = animation.FuncAnimation(f, ani_update, data_gen, interval=500)
plt.show()
    
    
    
    
    
    
    
    
    
    
    
    
    
    